package edu.utdallas_elearn_calendar.utdallas_elearn_calendar_app;


import edu.utdallas_elearn_calendar.utdallas_elearn_calendar_app.UniversityClass;
import edu.utdallas_elearn_calendar.utdallas_elearn_calendar_db.CalDbAdapter;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.TextView;

public class univ_classes extends Activity {
	// not sure what these do or why they are needed
	private static final int EDIT_CLASS = 0;
	private static final int VIEW_EVENTS = 1;
	private static final int VIEW_EVENT_TYPES = 2;
//	private static final int VIEW_PRIORITIES = 3;
	
	private CalDbAdapter dbHelper;
	public final static String FORMAT_DATE = "MM-dd-yy";
	public final static String FORMAT_DATE_TIME = "MM-dd-yy hh:mm";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.univ_classes);
        dbHelper = new CalDbAdapter(this);
		dbHelper.open();
		showClasses();
    }
    
	// Create the menu based on the XML defintion
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.class_menu, menu);
		return true;
	}
	
	// Reaction to the menu selection
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.edit_class:
			editClass();
			return true;
		case R.id.view_event:
			viewEvent();
			return true;
		case R.id.elearning_sync:
			elearningSync();
			return true;			
		case R.id.view_event_type:
			viewEventType();
			return true;		
//		case R.id.view_priority:
//			viewPriority();
//			return true;
		case R.id.view_settings:
			viewPreferences();
			return true;
		case R.id.reset_database:
			dbHelper.reset();
			showClasses();
			return true;
		case R.id.set_demo_database:
			dbHelper.reset();
			dbHelper.addDummy();
			showClasses();
			return true;			
		}
		return super.onMenuItemSelected(featureId, item);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.edit_class:
			editClass();
			return true;
		case R.id.view_event:
			viewEvent();
			return true;
		case R.id.elearning_sync:
			elearningSync();
			return true;			
		case R.id.view_event_type:
			viewEventType();
			return true;		
//		case R.id.view_priority:
//			viewPriority();
//			return true;
		case R.id.view_settings:
			viewPreferences();
			return true;
		case R.id.reset_database:
			dbHelper.reset();
			showClasses();
			return true;
		case R.id.set_demo_database:
			dbHelper.reset();
			dbHelper.addDummy();
			showClasses();
			return true;			
		}
		return super.onOptionsItemSelected(item);
	}
	
    private void showClasses()
    {
    	// first clear all the classes    	
    	ViewGroup layout = (ViewGroup) this.findViewById(R.id.table_univ_classes01);
    	layout.removeAllViews();
    	
    	setLastSyncText();
    	
    	// now get the new classes
    	ArrayList<UniversityClass> listClasses = new ArrayList<UniversityClass>();
        listClasses = GetUniversityClasses();
        
        
        for(UniversityClass univClass : listClasses)
        {	        
        	Button b = new Button(this.getApplicationContext());
	        b.setTextSize(17);
	        b.setId((int)univClass.UniversityClassId);
	        b.setText(univClass.Prefix + " " + univClass.ClassNumber + univClass.ClassSection + "\n" + univClass.Title);
        	b.setTag(univClass.UniversityClassId);        	
        	b.setOnClickListener(btnUniversityClassClick);
        	b.setOnLongClickListener(btnUnivLongClick);
	        layout.addView(b);
        }
    }
    
    private OnClickListener btnUniversityClassClick = new OnClickListener()
    {		
    	public void onClick(View v)
    	{
    		try
    		{	    	
        		Intent viewEvents = new Intent(v.getContext(), events.class);
        		Button b = (Button) v;
        		long id = Long.parseLong(b.getTag().toString());
	    		Log.d("univ_classes", "btnUnivLongEventClick: passing id to screen: " + id);	    		
	    		viewEvents.putExtra("_id", id);	    		
				startActivity(viewEvents);
    		}
    		catch(Exception e)
    		{
    			Log.e("MainScreen", "btnUnivLongEventClick error: " + e.toString());
    		}
    	}
    };
    
    private OnLongClickListener btnUnivLongClick = new OnLongClickListener()
    {		
    	public boolean onLongClick(View v)
    	{
    		try
    		{	    	
        		Intent viewClass = new Intent(v.getContext(), univ_class_edit.class);
        		Button b = (Button) v;
        		long id = Long.parseLong(b.getTag().toString());
        		
        		// do not update the MISC class
        		if (id == 0) {
        			return false;
        		}
	    		Log.d("MainScreen", "btnUnivClassEventClick: passing id to screen: " + id);
	    		viewClass.putExtra("_id", id);	    		
				startActivity(viewClass);
				return true;
    		}
    		catch(Exception e)
    		{
    			Log.e("MainScreen", "btnUnivClassEventClick error: " + e.toString());
    			return false;
    		}  		
    	}
    };

	public ArrayList<UniversityClass> GetUniversityClasses()
	{
		Log.i("DATABASE", "call to GetUniversityClasses");
		ArrayList<UniversityClass> listClasses = new ArrayList<UniversityClass>();
		
		try
		{			
			Cursor result = dbHelper.getAllClasses();
			startManagingCursor(result);
			
			if(result.getCount() > 0)
			{
				result.moveToFirst();
				do
				{
					UniversityClass univClass = new UniversityClass();
					univClass.UniversityClassId = result.getLong(result.getColumnIndexOrThrow(CalDbAdapter.ROW_ID));
					univClass.Prefix = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.CLASS_PREFIX));
					univClass.ClassNumber = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.CLASS_NUMBER));
					univClass.ClassSection = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.CLASS_SECTION));
					univClass.Semester = "";
					univClass.Title = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.CLASS_TITLE));
					listClasses.add(univClass);
				}
				while(result.moveToNext());
			}
			else
			{
				Log.i("DATABASE", "GetUniversityClasses: no classes found");
			}
			result.close();
		}
		catch(Exception e)
		{
			Log.e("DATABASE", "GetUniversityClasses error: " + e.toString() + e.getMessage());
		}
		return listClasses;
	}
    
    private void editClass() {
		Intent i = new Intent(this, univ_class_edit.class);
		startActivityForResult(i, EDIT_CLASS);
	}
    
    /**
     * onActivityResult is called once the startActivityForResult
     * activity returns
     */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		showClasses();
	}

	@Override
	protected void onPause() {
		super.onPause();
//		dbHelper.close();
	}	
	
	@Override
	protected void onResume() {
		super.onResume();
//		dbHelper.open();
		showClasses();
	}	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
		}
	}
	
	private void viewEvent() {
		Intent i = new Intent(this, events.class);
		startActivityForResult(i, VIEW_EVENTS);
	}
	
	private void elearningSync() {
		Intent i = new Intent(this, ElearningPortal.class);
		startActivity(i);
	}
	
	private void viewEventType() {
		Intent i = new Intent(this, event_types.class);
		startActivityForResult(i, VIEW_EVENT_TYPES);
	}	
	
//	private void viewPriority() {
//		Intent i = new Intent(this, priorities.class);
//		startActivityForResult(i, VIEW_PRIORITIES);
//	}
	
	private void viewPreferences() {
		Intent i = new Intent(this, AskUserPass.class);
		startActivity(i);
	}	
	
    private void setLastSyncText() {
    	String last_sync = "";
    	String status = "";
        TextView txtSync = (TextView) this.findViewById(R.id.txtClassesSyncTime);
        TextView txtStatus = (TextView) this.findViewById(R.id.txtClassesSyncSuccess);
        
    	try {
    		Cursor result;
			
			result = dbHelper.getElearnLog();
						
			startManagingCursor(result);

			if(result.getCount() > 0)
			{
				result.moveToFirst();
				last_sync = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.ELEARN_LOG_DATE));
				status = result.getString(result.getColumnIndexOrThrow(CalDbAdapter.ELEARN_LOG_STATUS));
				
				txtSync.setText("  " + last_sync);
		        txtStatus.setText("  " + status);
			}
			
			result.close();
    	} catch(Exception e) {
    		txtSync.setText(last_sync);
	        txtStatus.setText(status);
    	}
    } 
}